package middleware;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

import logging.Logging;

// Single thread that handles incoming client connections.
// Pushes all requests into queue which the DatabaseHandlers can fetch queries from
public class ClientHandler extends Thread{

	private Socket socket;
	private DataInputStream input;
	private PrintStream output;
	/**
	 * @uml.property  name="query"
	 */
	private String query;
	/**
	 * @uml.property  name="queue"
	 * @uml.associationEnd  
	 */
	private Queue queue;

	public ClientHandler(Socket s, Queue q) {

		socket = s;
		queue = q;
		
		try {
			output = new PrintStream(socket.getOutputStream());
			input = new DataInputStream(socket.getInputStream());
		} catch (IOException e) {
			System.err.println("Problems opening the input/output streams: " + e.getMessage());			
		}
	}

	/**
	 * Returns results to clients.
	 * @param str result string
	 */
	public void returnResult(String str) {

		output.println(str);
	}

	@SuppressWarnings("deprecation")
	public void run() {
		
		try {
			while ((query = input.readLine()) != null) {
				//System.out.println(query);
				queue.add(this);
			}
		} catch (IOException e) {
			System.err.println("ClientHandler client verreckt: " + e.getMessage());
		}
		
		try {
			input.close();
			output.close();
		} catch (IOException e) {
			System.err.println("Got problems with closing the input/output streams: " + e.getMessage());
		}

	}

	/**
	 * @return
	 * @uml.property  name="query"
	 */
	public String getQuery() {
		return query;
	}

	/**
	 * @param query
	 * @uml.property  name="query"
	 */
	public void setQuery(String query) {
		this.query = query;
	}


}
